package mrms.api.web.authentication;

import lombok.AllArgsConstructor;
import mrms.api.entity.UserEntity;
import mrms.api.repository.UserRepository;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Optional;

/**
 * @author lenchu
 * @date 2019/02/03
 */
@Component
@AllArgsConstructor
@Order(-100)
public class JwtAuthentication implements Authentication {
    private final JwtUtils jwtUtils;
    private final UserRepository userRepository;

    @Override
    public void authenticate(HttpServletRequest request, HttpServletResponse response, Map<String, Object> requestBody) {
        String jwt = request.getHeader("Authorization");
        if (jwt != null) {
            String uid = jwtUtils.getUserIdByJwtString(jwt);
            Optional<UserEntity> userEntity = userRepository.findById(uid);
            if (userEntity.isPresent()) {
                UserEntity u = userEntity.get();
                if (jwtUtils.verifyJwt(jwt, u.getPassword())) {
                    request.setAttribute("user", u);
                    return;
                }
            } else {
                return;
            }
        }
        return;
    }
}
